#include <string>
#include "User.h"
#include "command.h"
#include "Table.h"
#include "global.h"
using std::string;

User::User(int _u, const string &_n, const string _i){
	uid = _u;
	name = _n;
	icon = _i;
}

User::~User(){}

bool User::isOnline(){
	//return pConn->isOnline();
	return true;
}

bool User::isUserInRoom(){
	return ( pTable != NULL );
}

void User::setConn(ConnInfo *_c){
	assert(_c != NULL);
	pConn = _c;
}

int User::handleClose( void *args ){
	//pConn->close();
	return 0;
}

int User::handleRead( char *buf, unsigned int size, void *args ){
	if( size < 0){
		return -1;
	}

	static char tmpBuf[10240];
	buffer.pushData(buf, size);
	while(buffer.size() >= 8){
		buffer.lookData(tmpBuf, 8);
		ESInputPacket input;
		input.Copy(tmpBuf, 8);
		unsigned int allPacketLen = input.GetBodyLength() + 8;
		if(buffer.size() >= allPacketLen){
			buffer.popData(tmpBuf, allPacketLen);
			input.Copy(tmpBuf, allPacketLen);
			packetInput(input);
		}
	}
	return 0;
}
int User::handleWrite(){return 0;}

int User::handleTimeout(  ){return 0;}

//action
int User::UserLogin(int _t){
	pTable = s.getTablePtr(_t);
	if(pTable == NULL){
		return 0;
	}
	pTable->loginTable(this);
	sendUserLoginSucc();
	return 0;
}

int User::UserSit(ESInputPacket &input){
	int _s = input.ReadInt();
	if( pTable->sitTable(this, _s) < 0){
		return 0;
	}
	seatid = _s;
	sendUserSitSucc();
	return 0;
}

int User::UserStand(ESInputPacket &input){
	if( pTable->standTable(this) < 0){
		return 0;
	}
	return 0;
}

int User::UserLogout(ESInputPacket &input){
	if( pTable->logoutTable(this) < 0){
		return 0;
	}
	return 0;
}

int User::UserReady(){
	if( pTable->readyPlay(this) < 0 ){
		return -1;	
	}
	return 0;
}

int User::packetInput(ESInputPacket &input){
	unsigned short cmd = input.GetCmdType();
	switch (cmd)
	{
		case USER_LOGIN:
			return 0;//UserLogin(input);
		case USER_LOGOUT:
			return UserLogout(input);
		case USER_SIT:
			printf("user sit\n");
			return UserSit(input);
		case USER_STAND:
			return UserStand(input);
		case USER_READY:
			return UserReady();
	}
	return 0;
}

//#############################################################
void User::sendPacketData(ESOutputPacket &output){
	if( pConn == NULL ){
		return ;
	}
	pConn->sendPacketData(output.packet_buf(), output.packet_size());
}

void User::sendUserLoginSucc(){
	ESOutputPacket output;
	output.Begin(SRV_LOGIN_SUCC);
	output.End();
	sendPacketData(output);
}

void User::sendUserSitSucc(){
	ESOutputPacket output;
	output.Begin(SRV_SIT_SUCC);
	output.End();
	pConn->sendPacketData( output.packet_buf(), output.packet_size() );
}

